//
//  CWQIMNetManager.m
//  WCN
//
//  Created by 陈武琦 on 16/7/6.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "CWQIMNetManager.h"
#import "AFHTTPSessionManager.h"
#import "EMVoiceConverter.h"
#import "XHMessage.h"
static NSMutableArray *urlAndParamsCach;


#define weixinMessageHTTPSUrl    @"https://api.weixin.qq.com/cgi-bin/media/upload"
#define weixinMessageHTTPUrl    @"http://api.weixin.qq.com/cgi-bin/media/upload"

@implementation CWQIMNetManager
#pragma mark -------------IM获取图片、语音、视频------------------------------


+ (void)IMGET:(NSString *)URLString parameters:(id)params fromId:(NSString *)fromId progress:(void (^)(CGFloat))downloadProgress success:(void (^)(id))success failure:(void (^)(NSString *))failure {
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"weixinAccessToken"];
    if (token == nil) {
        [self getAccessTokenCompleted:^(NSString *accessToken) {
            [self GETMedia:URLString parameters:params accessToken:accessToken fromId:fromId progress:^(CGFloat percent) {
                if (downloadProgress) {
                    
                    downloadProgress(percent);
                }
            } success:^(id result) {
                if ([result isKindOfClass:[NSDictionary class]]) {
                    NSLog(@"token有问题");
                }else {
                    
                    success(result);
                }
            } failure:^(NSString *error) {
                failure(error);
            }];
        }];
    }else {
        [self GETMedia:URLString parameters:params accessToken:token fromId:fromId progress:^(CGFloat percent) {
            if (downloadProgress) {
                
                downloadProgress(percent);
            }
        } success:^(id result) {
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSLog(@"token有问题");
                [self getAccessTokenCompleted:^(NSString *accessToken) {
                    [self GETMedia:URLString parameters:params accessToken:token fromId:fromId progress:^(CGFloat percent) {
                        if (downloadProgress) {
                            
                            downloadProgress(percent);
                        }
                    } success:^(id result) {
                        if ([result isKindOfClass:[NSDictionary class]]) {
                            NSLog(@"token有问题");
                        }else {
                            
                            success(result);
                        }
                    } failure:^(NSString *error) {
                        failure(error);
                    }];
                }];
            }else {
                
                success(result);
            }
        } failure:^(NSString *error) {
            failure(error);
        }];
    }
    
}


#pragma mark -------------IM发送图片、语音、视频------------------------------


+ (void)IMPOST:(NSString *)URLString parameters:(NSDictionary *)params message:(XHMessage *)message progress:(void (^)(CGFloat))uploadPercent success:(void (^)(id))success failure:(void (^)(NSString *))failure {
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"weixinAccessToken"];
    if (token == nil) {
        [self getAccessTokenCompleted:^(NSString *accessToken) {
            [self sendMedia:weixinMessageHTTPSUrl accessToken:accessToken message:message progress:^(CGFloat percent) {
                uploadPercent(percent);
            } completationBlock:^(id obj) {
                if ([obj isKindOfClass:[NSDictionary class]]) {
                    NSLog(@"token有问题");
                }else {
                    
                    success(obj);
                }
            } failure:^(NSString *error) {
                failure(error);
            }];
            
        }];
    }else {
        
        [self sendMedia:weixinMessageHTTPSUrl accessToken:token message:message progress:^(CGFloat percent) {
            uploadPercent(percent);
        } completationBlock:^(id obj) {
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSLog(@"token有问题,在获取一次");
                [self getAccessTokenCompleted:^(NSString *accessToken) {
                    
                    [self sendMedia:weixinMessageHTTPSUrl accessToken:accessToken message:message progress:^(CGFloat percent) {
                        uploadPercent(percent);
                    } completationBlock:^(id obj) {
                        if ([obj isKindOfClass:[NSDictionary class]]) {
                            NSLog(@"未知问题");
                        }else {
                            
                            success(obj);
                        }
                    } failure:^(NSString *error) {
                        failure(error);
                    }];
                }];
            }else {
                
                success(obj);
            }
        } failure:^(NSString *error) {
            failure(error);
        }];
        
    }
    
}







//获取多媒体信息
+ (void)GETMedia:(NSString *)URLString parameters:(id)params accessToken:token fromId:(NSString *)fromId progress:(void (^)(CGFloat))downloadProgress success:(void (^)(id))success failure:(void (^)(NSString *))failure {
    
//    static int i = 0;
//    if (i!=0) {
//        return;
//    }
//    i++;
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"httpsCertificate" ofType:@"cer"];
    NSData * certData =[NSData dataWithContentsOfFile:cerPath];
    NSSet * certSet = [[NSSet alloc] initWithObjects:certData, nil];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // 是否允许,NO-- 不允许无效的证书
    [securityPolicy setAllowInvalidCertificates:YES];
    // 设置证书
    [securityPolicy setPinnedCertificates:certSet];
    manager.securityPolicy = securityPolicy;
    NSDictionary *dict = @{@"access_token":token ,@"media_id":params};
    NSLog(@"获取参数中************%@",dict);
    NSLog(@"获取店址:%@",URLString);
    
    NSString *keyStr =[NSString stringWithFormat:@"%@%@%@",URLString,token,params];
    if (!urlAndParamsCach) {
        urlAndParamsCach =[NSMutableArray array];
    }
//    if ([urlAndParamsCach containsObject:keyStr]) {
//        return;
//    }else{
//        [urlAndParamsCach addObject:keyStr];
//    }
//
    
//    NSData *data= [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://api.weixin.qq.com/cgi-bin/media/get?access_token=-GBzi1RtHQyazCYJGmrmWQokQMcRq4T3vbDPZ5yAz0SqvYse14KChuN3B5fqb0Hnlw8XDWhlrnKGWRblnPz9hwYwm782XFlCrDUdAvouFJeOkBDJdYhVNXckO3hjErFoJNDfADAFJZ&media_id=aq5BGbVpey1GrIhJsDrDjJgid0IXhUsjtVDOZ60hpKoZb3F1CA0EyhgJtKulde8B"]];
//    
//    [[WCNetworkAccessManager sharedMg] GET:@"https://api.weixin.qq.com/cgi-bin/media/get?access_token=-GBzi1RtHQyazCYJGmrmWQokQMcRq4T3vbDPZ5yAz0SqvYse14KChuN3B5fqb0Hnlw8XDWhlrnKGWRblnPz9hwYwm782XFlCrDUdAvouFJeOkBDJdYhVNXckO3hjErFoJNDfADAFJZ&media_id=aq5BGbVpey1GrIhJsDrDjJgid0IXhUsjtVDOZ60hpKoZb3F1CA0EyhgJtKulde8B" parameters:nil success:^(id responseObject) {
//        
//    } failure:^(NSString *msg) {
//        
//    } netError:nil always:^{
//        
//    }];
    
    
    
    weakSelf_define;
    [manager POST:URLString parameters:dict progress:^(NSProgress * _Nonnull progress) {
        // 给Progress添加监听 KVO
        CGFloat percent = 1.0 *progress.completedUnitCount / progress.totalUnitCount;
        downloadProgress(percent);
 
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSDictionary *headerDict = response.allHeaderFields;

        NSError *error;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
        if (result[@"errcode"]) {
            success(result);
        
        }else {
        
        //图片
        if ([headerDict[@"Content-Type"] isEqualToString:@"image/jpeg"]) {
            UIImage *photo = [UIImage imageWithData:responseObject];
            success(photo);
        }else if ([headerDict[@"Content-Type"] isEqualToString:@"audio/amr"]) {
            //语音
            NSString *voicePath = [weakSelf getVoiceStorePathWithFromId:fromId];
            NSString *amrPath = [voicePath stringByAppendingString:@"amr"];
            //将数据保存到本地指定位置
            BOOL write = [responseObject writeToFile:amrPath atomically:YES];
            if (write) {
                NSString *wavPath = [voicePath stringByAppendingString:@"wav"];
                //转格式
                if ([EMVoiceConverter isAMRFile:amrPath]) {
                    
                    if ([EMVoiceConverter amrToWav:amrPath wavSavePath:wavPath] == 0){
                        
                        [[NSFileManager defaultManager] removeItemAtPath:amrPath error:nil];
                        success(wavPath);
                    }else
                        NSLog(@"amr转`失败");
                    
                    }
                }
        }else if ([headerDict[@"Content-Type"] isEqualToString:@"text/plain"]){
            //content-Type = text/plain
            //视频链接
            NSError *error;
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
            if (result[@"errcode"]) {
                NSLog(@"%@",result);
                return;
            }
            success(result[@"video_url"]);
            
        }else {
        //视频文件
    
            NSString *videoPath = [[self getVoiceStorePathWithFromId:fromId] stringByAppendingString:@"mp4"];
            
            BOOL write = [responseObject writeToFile:videoPath atomically:YES];
            if (write) {
                success(videoPath);
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [urlAndParamsCach removeObject:keyStr];
        CoreSVPError(error.localizedDescription);
    }];

}








//发送多媒体(图片，声音)
+ (void)sendMedia:(NSString *)URLString accessToken:(NSString *)token message:(XHMessage *)message progress:(void (^)(CGFloat))uploadPercent completationBlock:(void (^)(id))completationBlock failure:(void (^)(NSString *))failure {


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"httpsCertificate" ofType:@"cer"];
    NSData * certData =[NSData dataWithContentsOfFile:cerPath];
    NSSet * certSet = [[NSSet alloc] initWithObjects:certData, nil];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // 是否允许,NO-- 不允许无效的证书
    [securityPolicy setAllowInvalidCertificates:YES];
    // 设置证书
    [securityPolicy setPinnedCertificates:certSet];
    manager.securityPolicy = securityPolicy;
    NSDictionary *dict;
    
    switch (message.messageMediaType) {
        case XHBubbleMessageMediaTypePhoto:
            dict = @{@"type":@"image", @"access_token":token};
            break;
        case XHBubbleMessageMediaTypeVideo:
            //先传缩略图
            dict = @{@"type":@"thumb", @"access_token":token};
            break;
            
        case XHBubbleMessageMediaTypeVoice:
            dict = @{@"type":@"voice", @"access_token":token};
            break;
            
        default:
            break;
    }
    
            
            [manager POST:weixinMessageHTTPSUrl parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                
                switch (message.messageMediaType) {
                    case XHBubbleMessageMediaTypePhoto:{
                        
                        //上床图片
                        UIImage *image = message.photo;
                        NSData *imageData = UIImagePNGRepresentation(image);
                        if (!imageData) {
                            imageData = UIImageJPEGRepresentation(image, 1);
                        }
                        CGFloat length = [imageData length]/1024.0;
                        length = length/1024.0;
                        if (length > 2) {
                            imageData = UIImageJPEGRepresentation(image, 2.0/length);
                        }
                        [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename.png" mimeType:@"image/png"];
                        
                    }
                        
                        break;
                    case XHBubbleMessageMediaTypeVideo:
                    {
                        //上传说略图
                        UIImage *image = message.videoConverPhoto;
                        NSData *imageData = UIImagePNGRepresentation(image);
                        if (!imageData) {
                            imageData = UIImageJPEGRepresentation(image, 1);
                        }
                        CGFloat length = [imageData length]/1024.0;
                        
                        if (length > 64) {
                            imageData = UIImageJPEGRepresentation(image, 64/length);
                            [formData appendPartWithFileData:imageData name:@"file" fileName:@"thumb.png" mimeType:@"image/png"];
                        }
                        
                    }
                        break;
                        
                    case XHBubbleMessageMediaTypeVoice:{
                        
                        NSString *voicePath = message.voicePath;
                        NSString *path = [voicePath substringFromIndex:[voicePath length]-34];
                        
                        NSURL *url = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"%@", path]];
                        
                        [formData appendPartWithFileURL:url name:@"file" fileName:@"voice.mp3" mimeType:@"amr/mp3" error:nil];
                        
                    }
                        
                        break;
                        
                    default:
                        break;
                }
                
                
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                //上传进度
                // 给Progress添加监听 KVO
                CGFloat percent = 1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
                uploadPercent(percent);
                
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                
                NSError *error;
                NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
                if (result[@"errcode"]) completationBlock(result);
                else {
                    if (message.messageMediaType == XHBubbleMessageMediaTypeVideo) {
                        
                        [self sendVideo:URLString type:@"video" accessToken:token message:message progress:nil success:^(id obj) {
                            completationBlock(@[obj[@"media_id"],result[@"media_id"]]);
                        } failure:^(NSString *error) {
                            
                        }];
                    }else {
                        
                        completationBlock(result[@"media_id"]);
                    }
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failure(@"网络问题");
                NSLog(@"%@",error);
            }];


}






// 发送视频
+ (void)sendVideo:(NSString *)URLString type:(NSString *)type accessToken:(NSString *)token message:(XHMessage *)message progress:(void (^)(CGFloat))uploadPercent success:(void (^)(id))success failure:(void (^)(NSString *))failure {
    
    NSDictionary *param = @{@"type":type, @"access_token":token};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;
    [manager POST:weixinMessageHTTPUrl parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 上传视频
        NSString *videoPath = message.videoPath;
        NSString *path = [videoPath substringFromIndex:[videoPath length]-34];
        NSURL *url = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"%@", path]];
        [formData appendPartWithFileURL:url name:@"file" fileName:@"video.mp4" mimeType:@"application/octet-stream" error:nil];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSError *error;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
        if (result[@"errcode"]) {
            NSLog(@"%@",result);
        }else {
            success(result[@"media_id"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
}

//获取微信 accesstoken
+(void)getAccessTokenCompleted:(void (^)(NSString *))callBackAccessToken{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;
    
//    NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:[self getConfigFilePath]];
//    NSString *model = configs[@"MODEL"];
//    NSDictionary *urls = configs[@"URLS"];
//    NSDictionary *payUrls = configs[@"PAYS"];
//    _bathURL = urls[model];

//    NSString *url =[]
  

    
    NSString *configUrl =[[WCNetworkAccessManager sharedMg] getWexinAccessTokenApi];
    

    [manager POST:configUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *token = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"weixinAccessToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        callBackAccessToken(token);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        CoreSVPError(error.localizedDescription);
    }];
}





+ (NSString *)getVoiceStorePathWithFromId:(NSString *)fromeId {
    
    NSString *recorderPath = nil;
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    recorderPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", fromeId];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:recorderPath]) {
       BOOL create = [[NSFileManager defaultManager] createDirectoryAtPath:recorderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if (create) {
            recorderPath = [recorderPath stringByAppendingFormat:@"/%@.",[formater stringFromDate:[NSDate date]]];
        }else {
         recorderPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@/%@.", fromeId ,[formater stringFromDate:[NSDate date]]];
        }
    }else {
         recorderPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.", [formater stringFromDate:[NSDate date]]];
    
    }
    return recorderPath;
}



@end
